<template>
  <view class="container">
    <view
      ref="slider"
      class="ba-slider"
      :style="{ height: height + 'rpx', width: width + 'rpx' }"
    >
	  <image v-if="afterImageSrc && !afterImageBase64" :src="afterImageSrc" mode="scaleToFill" class="full-image" />
      <image v-else :src="afterImageBase64" mode="scaleToFill" class="full-image" />
      <view class="resize" :style="{ width: resizeWidth + '%' }">
        <image 
          :src="beforeImageSrc"
          mode="scaleToFill"
          class="full-image" 
          :style="{ width: width + 'rpx' }" 
        />
      </view>
      <view
        ref="handle"
        class="handle"
        :style="{ left: resizeWidth + '%' }"
        @touchstart="startDrag"
        @touchmove="handleDrag"
        @touchend="endDrag"
        @touchcancel="endDrag"
      ></view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ImageComparsionSlide',
  props: {
    beforeImageSrc: {
      type: String,
      default: '/static/func/defaultBefore.jpg'
    },
    afterImageSrc: {
      type: String,
      default: '/static/func/defaultAfter.jpg'
    },
    height: {
      type: Number,
      default: 800 // 使用rpx单位
    },
    width: {
      type: Number,
      default: 750 // 屏幕宽度
    }
  },
  data() {
    return {
      resizeWidth: 50, // 初始分割比例
      isDragging: false,
      startX: 0,
      startWidth: 0,
      sliderWidth: 0,
      sliderLeft: 0, // 滑块容器左侧位置
      sliderRect: null, // 滑块容器尺寸信息
	  beforeImageBase64: '',
	  afterImageBase64: ''
    }
  },
  onReady() {
    // 获取容器尺寸信息
    this.getSliderRect()
  },
  watch: {
	  afterImageSrc: {
		  handler(val) {
			this.translateUrlToBase64(val)
		  },
		  immediate: false,
	  },
  },
  methods: {
	  // 转换本地图片或网络图片为 base64格式
	  async translateUrlToBase64(imageUrl) {
	      const _this = this;
		  if(imageUrl === '') return '';
	      try {
	        // 自动判断是否为网络图片（以http://或https://开头）
	        const isNetwork = /^https?:\/\//.test(imageUrl);
	        let tempFilePath;
	        
	        if (isNetwork) {
	          // 网络图片：下载到临时路径
	          const { tempFilePath: downloadPath, statusCode } = await uni.downloadFile({ url: imageUrl });
	          if (statusCode !== 200) {
	            throw new Error(`网络图片下载失败，状态码: ${statusCode}`);
	          }
	          tempFilePath = downloadPath;
	        } else {
	          // 本地图片：直接使用传入的本地路径
	          tempFilePath = imageUrl;
	        }
			
	        // 读取文件并转换为Base64
	        const base64Data = uni.getFileSystemManager().readFileSync(tempFilePath, 'base64');
	        
	        // 提取格式并生成完整Base64
	        const format = (imageUrl.match(/\.(\w+)$/) || [])[1]?.toLowerCase() || 'jpeg';
	        const mimeType = format === 'svg' ? 'svg+xml' : format;
	        _this.afterImageBase64 = `data:image/${mimeType};base64,${base64Data}`;
	    
	      } catch (error) {
	        console.error('图片转换失败:', error.message);
	      }
	  },
    // 获取滑块容器尺寸
    getSliderRect() {
      const query = uni.createSelectorQuery().in(this)
      query.select('.ba-slider').boundingClientRect(res => {
        if (res) {
          this.sliderRect = res
          this.sliderWidth = res.width
          this.sliderLeft = res.left
        }
      }).exec()
    },
    
    startDrag(e) {
      // 如果尚未获取到容器尺寸，尝试再次获取
      if (!this.sliderRect) {
        this.getSliderRect()
        return
      }
      
      this.isDragging = true
      this.startX = e.touches[0].clientX
      this.startWidth = this.resizeWidth
      
      // 阻止事件冒泡，避免触发父元素的事件
      e.stopPropagation()
      e.preventDefault()
    },
    
    handleDrag(e) {
      if (!this.isDragging || !this.sliderRect) return
      
      // 防止页面滚动
      e.preventDefault()
      
      const touchX = e.touches[0].clientX
      // 计算相对于滑块容器的位置
      const relativeX = touchX - this.sliderLeft
      
      // 计算新的宽度百分比
      let newWidth = (relativeX / this.sliderWidth) * 100
      
      // 边界检查
      newWidth = Math.max(0, Math.min(100, newWidth))
      this.resizeWidth = newWidth
    },
    
    endDrag() {
      this.isDragging = false
    }
  },
  onUnload() {
    // 清理工作
    this.isDragging = false
  }
}
</script>



<style scoped lang="scss">
.container {
  width: 100%;
  overflow: hidden;
}

.ba-slider {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border: 2rpx solid #686363;
}

.full-image {
  width: 100%;
  height: 100%;
  user-select: none;
}

.resize {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  overflow: hidden;
  border-right: 2rpx solid #ffffffa6;
}

.handle {
  cursor: ew-resize;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate3d(-50%, -50%, 0);
  color: #000;
  background: rgba(255, 255, 255, 0.8);
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  box-shadow: 0 0 12rpx rgba(0, 0, 0, 0.2);
  
  // 使用伪元素创建箭头
  &::after,
  &::before {
    content: '';
    position: absolute;
    width: 20rpx;
    height: 20rpx;
    top: 50%;
    border-top: solid 4rpx;
    border-left: solid 4rpx;
    transform-origin: 0 0;
  }
  
  &::before {
    left: 12rpx;
    transform: rotate(-45deg);
  }
  
  &::after {
    left: 68rpx;
    transform: rotate(135deg);
  }
}
</style>